package com.ssm.web;


import com.ssm.entity.Log;
import com.ssm.entity.User;
import com.ssm.service.FileService;
import com.ssm.service.LogService;
import com.ssm.service.UserService;
import com.zhuozhengsoft.pageoffice.FileSaver;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;


/**
 * Created by 小灰灰 on 2017/7/31.
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired(required = false)
    FileService fileService;
    @Autowired
    UserService userService;
    @Autowired
    LogService logService;

    @RequestMapping(value = "/importfile", method = RequestMethod.GET)
    private String importfile() {
        return "importfile";
    }

    @RequestMapping(value = "/upload.do/{username}")
    public String upload(@PathVariable ("username")String username,
                         @RequestParam(value = "file", required = false) MultipartFile file,
                         HttpServletRequest request, Model model) throws IOException {

        /*System.out.println("开始");*/
        String path = request.getSession().getServletContext().getRealPath("/upload");
        String fileName = file.getOriginalFilename();
        /*System.out.println(fileName);
        System.out.println(path);*/
        File targetFile = new File(path, fileName);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        com.ssm.entity.File file1=new com.ssm.entity.File();
        Timestamp timestamp =new Timestamp(System.currentTimeMillis());
        /*System.out.print(username);*/
        User user = userService.queryByUsername(username);
        /*System.out.print(user.getId());*/

        file1.setFileName(fileName);
        file1.setCreateTime(timestamp);
        file1.setUserId(user.getId());
        file1.setAlterTime(timestamp);
        fileService.addToDatabase(file1);

        Log log=new Log();
        log.setUserId(user.getId());
        String opertionstring="用户"+user.getUsername()+"提交了文件"+fileName;
        log.setOperations(opertionstring);
        log.setTime(timestamp);
        logService.addLog(log);


       if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("file1",file1);
       getFileList(request,model);

        return "welcome";
    }


    /*管理员查询所有文件*/
    @RequestMapping(value = "/query")
    public String queryDoc(Model model, HttpServletRequest request){
        List<com.ssm.entity.File> fileList= fileService.queryAllDoc();
        /*fileList=fileService.queryAllDoc();*/
        /*HttpSession session=request.getSession();*/
        request.setAttribute("fileList",fileList);
        /*model.addAttribute("fileList", fileList);*/
        return"showDoc";
    }

    /*在线查看文件*/
    @RequestMapping(value = "/queryAndEdit/{file.fileId}")
    public String queryAndEditDoc (@PathVariable("file.fileId")  int  fileId,HttpServletRequest request){
        com.ssm.entity.File file=fileService.queryByFileid(fileId);
        HttpSession session=request.getSession();
        session.setAttribute("file",file);

        User user=(User)session.getAttribute("user");
        Log log=new Log();
        log.setUserId(user.getId());
        String opertionstring="用户"+user.getUsername()+"查看了文件 "+file.getFileName();
        log.setOperations(opertionstring);
        Timestamp timestamp =new Timestamp(System.currentTimeMillis());
        log.setTime(timestamp);
        logService.addLog(log);

        return "showAndEditDoc";
    }


    /*保存修改*/
    @RequestMapping(value = "/save")
    public String saveDoc (HttpServletRequest request, HttpServletResponse response){
        FileSaver fs=new FileSaver(request,response);
        String filePath = request.getSession().getServletContext().getRealPath("/upload/")+fs.getFileName();
        /*System.out.print(filePath);*/
        fs.saveToFile(request.getSession().getServletContext().getRealPath("/upload/")+fs.getFileName());
        fs.close();
        return "showAndEditDoc";
    }

    /*下载文件*/
    @RequestMapping(value="/download/{file.fileName}")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @PathVariable("file.fileName") String filename,
                                           Model model)throws Exception {
        //下载文件路径
        String path = request.getServletContext().getRealPath("/upload");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }


    /*删除文件*/
    @RequestMapping(value = "/delete/{file.fileId}")
    public String deleteDoc(@PathVariable("file.fileId")  int  fileId, Model model,HttpServletRequest request){
        com.ssm.entity.File file=fileService.queryByFileid(fileId);
        fileService.deleteDoc(fileId);
        getFileList(request,model);

        HttpSession session=request.getSession();
        User user=(User)session.getAttribute("user");
        Log log=new Log();
        log.setUserId(user.getId());
        String opertionstring="用户"+user.getUsername()+"删除了文件 "+file.getFileName();
        log.setOperations(opertionstring);
        Timestamp timestamp =new Timestamp(System.currentTimeMillis());
        log.setTime(timestamp);
        logService.addLog(log);

        /*System.out.print("删除成功！");*/
        return "welcome";
    }


    /*  此模块用于测试模糊查询文档*/

    @RequestMapping(value = "/testFileSearch", method = RequestMethod.GET)
    private String testFileSearchPage(User user, Model model) {
        return "testFileSearch";
    }
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    private String showUserPage(User user, Model model) {
        return "welcome";
    }
    @RequestMapping(value="/welcome" ,method = RequestMethod.POST)
    public String lookTest( HttpServletRequest request, Model model) throws Exception {
        String keyName;
        keyName=request.getParameter("keyName");
        System.out.println(keyName);
        List<com.ssm.entity.File> fileList =fileService.queryByKeyName(keyName);
        // System.out.print(fileList.get(0).getFileName());
        //  List<File> fileList =fileService.getAllFile();
        model.addAttribute("fileList", fileList);
        System.out.print(fileList.get(0).getFileName());
        return "welcome";
    }


    /**
     * 获取文件列表的方法
     *
     * */
    public void getFileList(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        String username = session.getAttribute("username").toString();
        User user = userService.queryByUsername(username);

        List<com.ssm.entity.File> fileList = fileService.queryByUserName(user.getUsername());
        model.addAttribute("fileList",fileList);
    }
}
